/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.support.wx;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.yanlight.Constants;
import com.yanlight.support.pay.PayNotify;
import com.yanlight.support.pay.PayNotifyHandler;
import com.yanlight.support.pay.PayNotifyRequest;
import com.yanlight.support.wx.request.WxPayNotifyRequest;
import com.yanlight.support.wx.response.WxPayNotifyResponse;
import com.yanlight.type.PayType;
import com.yanlight.util.DateTimeUtil;
import com.yanlight.util.ToolsUtil;
import com.yanlight.util.WebUtil;
import com.yanlight.util.XmlUtil;

/**
 * 
 * @author haolw
 * @time 2017/10/27
 */
public class WxpayNotifyHandler implements PayNotifyHandler {
	private static WxpayNotifyHandler handler = new WxpayNotifyHandler();

	private WxpayNotifyHandler() {
	}

	public static WxpayNotifyHandler getInstance() {
		return handler;
	}

	@Override
	public void handPayNotify(String packets, HttpServletResponse response, PayNotify notify) {
		WxPayNotifyRequest notifyRequest = new WxPayNotifyRequest(packets);
		String apikey = WxConstants.apiKey;
		if (notifyRequest.verifySign(apikey)) {
			String returnCode = notifyRequest.getReturnCode();
			String resultCode = notifyRequest.getResultCode();
			String returnMsg = notifyRequest.getReturnMsg();
			WxPayNotifyResponse notifyResponse = new WxPayNotifyResponse();
			if (Constants.SUCCESS.toUpperCase().equals(resultCode)) {
				Integer totalFee = Integer.valueOf(notifyRequest.getTotalFee());
				String time = notifyRequest.getTimeEnd();
				String payTime = DateTimeUtil.conver(time, Constants.format2, Constants.format1);
				PayNotifyRequest payNotifyRequest = new PayNotifyRequest();
				payNotifyRequest.setOutTradeNo(notifyRequest.getOutTradeNo());
				payNotifyRequest.setBuyerId(notifyRequest.getOpenId());
				payNotifyRequest.setTotalFee(ToolsUtil.convertFee(totalFee));
				payNotifyRequest.setTransactionNo(notifyRequest.getTransactionId());
				payNotifyRequest.setPayTime(payTime);
				payNotifyRequest.setPayType(PayType.WXPAY.getType());
				boolean internalResult = notify.processPayNotify(payNotifyRequest);
				if (internalResult) {
					if (StringUtils.isNotBlank(returnMsg)) {
						notifyResponse.setReturn_msg(returnMsg);
					}
					notifyResponse.setReturn_code(returnCode);
					String result = XmlUtil.objectToXmlWithCDATA(notifyResponse);
					WebUtil.renderText(response, result);
				}
			}
		} else {
			WebUtil.renderText(response, Constants.FAIL);
		}
	}

}
